<template>
  <view class="Mall4j personal-information">
    <!-- 头像 -->
    <!--		<view class="head-portrait clearfix">-->
    <!--			<view class="head-txt">{{ i18n.avatar }}</view>-->
    <!--			<view class="station-photo-con">-->
    <!--				<view class="add-img" @tap="getUploadImg">-->
    <!--					<image class="add-img-icon"-->
    <!--						:src="photoFiles?photoFiles:( pic? pic : 'https://mall-1312577323.cos.ap-chengdu.myqcloud.com/mall/images/icon/head04.png')" mode="widthFix" />-->
    <!--				</view>-->
    <!--			</view>-->
    <!--		</view>-->
    <view class="persone-info">
      <!-- 头像 -->
      <view class="head-portrait clearfix">
        <view class="head-txt">{{ i18n.avatar }}</view>
        <view class="station-photo-con">
          <view class="add-img" @tap="getUploadImg">
            <image class="add-img-icon" :src="photoFiles?photoFiles:( pic? pic : 'https://mall-1312577323.cos.ap-chengdu.myqcloud.com/mall/images/icon/head04.png')" mode="widthFix" />
          </view>
        </view>
      </view>
      <!-- 用户名 -->
      <view v-if="userName" class="msg-item user-name">
        <view class="msg-item-txt">{{ i18n.userName }}</view>
        <view class="right-arrow">
          <input type="text" class="choose-value" :value="userName" disabled @click="handleUserNameClick">
        </view>
      </view>
      <!-- 昵称 -->
      <view class="msg-item nickname">
        <view class="msg-item-txt">{{ i18n.nickname }}</view>
        <view class="right-arrow">
          <input type="text" maxlength="15" class="choose-value" :value="nickName" @input="getNickNameInt">
          <!-- <view class="choose-value">
            {{nickName}}
          </view> -->
          <!-- <image src="https://mall-1312577323.cos.ap-chengdu.myqcloud.com/mall/images/icon/more.png" class="right-arrow-img"></image> -->
        </view>
      </view>
      <!-- 性别 -->
      <!-- <view class="msg-item gender">
				<picker class="gender-picker" @change="bindPickerChange" :value="sex" :range="genderArray">
					<view class="msg-item-txt">{{i18n.gender}}</view>
					<view class="right-arrow">
						<view class="choose-value">{{genderArray[sex]}}</view>
						<image src="https://mall-1312577323.cos.ap-chengdu.myqcloud.com/mall/images/icon/more.png" class="right-arrow-img"></image>
					</view>
				</picker>
			</view> -->
      <view class="section" @tap="translate">
        <text>{{ i18n.gender }}</text>
        <view class="pca">{{ genderArray[sex] }}</view>
        <template v-if="showPicker">
          <view class="animation-element-wrapper" :animation="animation" :style="'visibility:' + (show ? 'visible':'hidden')" @tap.stop="hiddenFloatView">
            <view class="animation-element" @tap.stop="nono">
              <text class="right-bt" @tap.stop="hiddenFloatView">{{ i18n.confirm }}</text>
              <view class="line" />
              <picker-view indicator-style="height: 50px;" @change="bindChange" @tap.stop="nono">
                <picker-view-column>
                  <view v-for="(item, index) in genderArray" :key="index">{{ item }}</view>
                </picker-view-column>
              </picker-view>
            </view>
          </view>
        </template>
        <view class="arrow">
          <image src="https://mall-1312577323.cos.ap-chengdu.myqcloud.com/mall/images/icon/more.png" />
        </view>
      </view>
      <!-- 账号注销 -->

      <view class="account">
        <text>定向推送</text>
        <view>
          <!--          <switch checked @change="updatePersonal" />-->
          <switch color="#f39828" :checked="isSwitchOn" @change="updatePersonal"></switch>
        </view>
      </view>
      <view class="account" @tap="onCancellation">
        <text>账号注销</text>
        <view class="arrow">
          <image src="https://mall-1312577323.cos.ap-chengdu.myqcloud.com/mall/images/icon/more.png" />
        </view>
      </view>
      <view class="account" @tap="logout">
        <text>{{i18n.signOut}}</text>
        <view class="arrow">
          <image src="https://mall-1312577323.cos.ap-chengdu.myqcloud.com/mall/images/icon/more.png" />
        </view>
      </view>
      <!-- 电话 -->
      <!-- <view class="msg-item phone">
        <view class="msg-item-txt">电话</view>
        <view class="phone-num" v-if="phoneNumber">
          <button class="get-phone-num" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">
            授权获取手机号
          </button>
        </view>
        <view class="phone-num" v-if="!phoneNumber">{{phoneNumber}}</view>
      </view> -->
      <!-- 生日 -->
      <!-- <view class="msg-item birthday">
        <picker class="birthday-picker" mode="date" :value="date" start="" end="" @change="bindDateChange">
          <view class="msg-item-txt">生日</view>
          <view class="right-arrow">
            <view class="choose-value" v-if="date">{{date}}</view>
            <view class="choose-value" v-if="!date"></view>
            <image src="https://mall-1312577323.cos.ap-chengdu.myqcloud.com/mall/images/icon/more.png" class="right-arrow-img"></image>
          </view>
        </picker>
      </view> -->
    </view>
    <view v-if="isChange" class="confirm red-btn" @tap="setUserInfo">{{ i18n.confirm }}</view>
  </view>
</template>

<script module="wxs" lang="wxs" src="../../wxs/number.wxs">
</script>

<script>
//index.js
//获取应用实例
import { createLogger } from 'vuex'

var http = require("../../utils/http.js");
var config = require("../../utils/config.js");
var util = require("../../utils/util.js");
const app = getApp().globalData;
var t = 0;
var show = false;
var moveY = 200;

export default {
  data () {
    return {
      userId: '',
      photoFiles: '',
      // genderArray: ['男', '女'],
      // genderArray: [this.i18n.female, this.i18n.male],
      // 不能直接这样的，要读取后保存进来
      genderArray: [],
      genderIndex: 0,
      date: '2020-01-01', //用户生日
      dateIndex: 0,

      // birthDate: '',   //用户生日
      userName: '',
      nickName: '', //用户昵称
      score: 0, //积分
      sex: 0, //性别
      oldSex: '', //原先性别
      sexNumber: 0, // 判断有无滑动
      phoneNumber: '', //手机号
      countryCode: '', //区号
      pic: '',
      isChange: false, // 是否修改用户信息
      animation: "",
      show: "",
      isSwitchOn: false,
      showPicker: false
    };
  },

  components: {},
  props: {},

  computed: {
    i18n () {
      return this.$t('index')
    }
  },

  onLoad: function () {
    //加载会员信息
    this.genderArray.push(this.i18n.female)
    this.genderArray.push(this.i18n.male)
    this.queryUserInfo()
  },
  onShow: function () {
    //头部导航标题
    uni.setNavigationBarTitle({
      title: this.i18n.personalData
    });
  },
  onHide: function () {
    this.showPicker = false
  },
  onReady: function () {
    this.animation = wx.createAnimation({
      transformOrigin: "50% 50%",
      duration: 0,
      timingFunction: "ease",
      delay: 0
    });
    this.animation.translateY(200 + 'vh').step();
    this.setData({
      animation: this.animation.export(),
      show: show
    });
  },
  methods: {
    /**
     * 用户名点击事件
     */
    handleUserNameClick () {
      uni.showToast({
        title: this.i18n.userNameCannotChange,
        icon: 'none'
      })
    },
    /**
     * 上传图片
     */
    getUploadImg: function (e) {
      // let agree = this.getAgree()
      // if (!agree) {
      //   return
      // }
      uni.chooseImage({
        count: 1, // 默认9
        sizeType: ['compressed'],
        sourceType: ['album'],
        success: (res) => {
          var tempFilePaths = res.tempFilePaths
          var params = {
            url: "/p/file/upload",
            filePath: tempFilePaths[0],
            name: 'file',
            callBack: (res2) => {
              this.photoFiles = res2.resourcesUrl + res2.filePath,
                this._photoFiles = res2.filePath
              this.isChange = true
            },
          };
          if (util.lessThan2M(res.tempFiles)) {
            http.upload(params);
          }
        },
        fail: (failMsg) => {
          console.log(failMsg)
        }
      })


    },
    getAgree: function () {
      let agree = uni.getStorageSync('agree')
      if (agree) {
        return true;
        uni.setStorageSync('agree', true)
      } else {
        uni.showModal({
          title: '提示',
          content: '需要相册图片作为头像,是否授权存储权限',
          success: function (res) {
            if (res.confirm) {
              uni.setStorageSync('agree', true)
              uni.showToast({
                title: "请再次点击以授权存储功能",
                icon: 'none'
              })
              return true;
            } else if (res.cancel) {
              uni.setStorageSync('agree', false)
              return false;
            }
          }
        });
      }
    },

    // 获取用户信息
    queryUserInfo: function () {
      var params = {
        url: "/p/user/userInfo",
        method: "GET",
        data: {},
        callBack: (res) => {
          this.userId = res.userId
          this.date = res.birthDate //用户生日
          this.nickName = res.nickName //用户昵称
          this.score = res.score //积分
          this.sex = Number(res.sex) //性别
          this.oldSex = Number(res.sex) //原本的性别
          this.phoneNumber = res.userMobile //用户手机号
          this.pic = res.pic
          this.isSwitchOn = res.personalStatus
          this.userName = res.userName
          if (!res.birthDate) {
            // 获取当前日期并改变日期展示格式
            var curDate = new Date();
            var seperator1 = "-";
            var month = curDate.getMonth() + 1 < 10 ? "0" + (curDate.getMonth() + 1) : curDate
              .getMonth() + 1; //截取月份
            var strDate = curDate.getDate() < 10 ? "0" + curDate.getDate() : curDate
              .getDate(); //截取日期
            this.date = curDate.getFullYear() + seperator1 + month + seperator1 +
              strDate //将年月日用'-'拼接起来
            console.log(this.date)
          }
        }
      };
      http.request(params);
    },

    //移动按钮点击事件
    translate: function (e) {
      if (t == 0) {
        moveY = 0;
        show = false;
        t = 1;
      } else {
        moveY = 200;
        show = true;
        t = 0;
      }
      this.setData({
        show: true,
        showPicker: true
      }); // this.animation.translate(arr[0], arr[1]).step();


      this.animationEvents(this, moveY, show);
    },

    //隐藏弹窗浮层
    hiddenFloatView (e) {
      if (!this.sexNumber) {
        this.setData({
          sex: 0
        })
        if (this.sex != this.oldSex) {
          this.isChange = true
        }
      }
      moveY = 200;
      show = true;
      t = 0;
      this.animationEvents(this, moveY, show);
    },

    //动画事件
    animationEvents: function (that, moveY, show) {
      that.animation = wx.createAnimation({
        transformOrigin: "50% 50%",
        duration: 400,
        timingFunction: "ease",
        delay: 0
      });
      that.animation.translateY(moveY + 'vh').step();
      that.setData({
        animation: that.animation.export()
      });
    },

    //用户昵称
    getNickNameInt: function (e) {
      this.nickName = e.detail.value
      this.isChange = true
    },

    // 选择性别
    bindChange: function (e) {
      this.sex = e.detail.value[0]
      this.setData({
        sexNumber: this.sexNumber += 1
      })
      if (this.sex != Number(this.oldSex)) {
        this.isChange = true
      } else {
        this.isChange = false
      }
    },

    // 选择日期
    bindDateChange: function (e) {
      this.isChange = true
      this.date = e.detail.value
    },

    /**
     * 设置用户信息
     */
    setUserInfo: function () {
      if (!this.nickName.trim()) {
        uni.showToast({
          title: this.i18n.nicknameEmptyTips,
          icon: 'none',
        })
        return
      }
      if (this.isChange) {
        var params = {
          url: "/p/user/setUserInfo",
          method: "PUT",
          data: {
            avatarUrl: this.photoFiles,
            birthDate: this.date,
            sex: this.sex,
            nickName: this.nickName
          },
          callBack: (res) => {
            uni.showToast({
              title: this.i18n.successfullyModified,
              icon: 'none',
              duration: 1000
            })
            setTimeout(() => {
              this.queryUserInfo()
              this.$Router.pushTab('/pages/user/user')
            }, 1000)
          }
        };
        http.request(params);
      }
    },
    /**
     * 修改用户是否同意开启个性化设置
     */
    updatePersonal: function (state) {
      var params = {
        url: "/p/user/update/personal",
        method: "POST",
        data: {
          userId: this.userId,
          personalStatus: Number(state.detail.value)
        },
        callBack: (res) => {
          console.log(res)
        }
      }
      http.request(params);
    },
    /* 前往账号注销页面 */
    onCancellation () {
      uni.navigateTo({
        url: '/pages/cancellation-page/cancellation-page'
      })
    },
    logout: function () {
      util.tapLog(3)

      // 请求退出登陆接口
      http.request({
        url: '/logOut',
        method: 'POST',
        callBack: res => {
          util.removeTabBadge()
          uni.removeStorageSync('loginResult')
          uni.removeStorageSync('token')
          uni.removeStorageSync('tempToken')
          uni.removeStorageSync('recentSearch')
          uni.removeStorageSync('code')

          // 重置uuid、uuidSession、sessionTimeStamp、step、flowAnalysisLogDto
          uni.setStorageSync('uuid', util.getUuid())
          uni.setStorageSync('uuidSession', util.getUuid())
          uni.setStorageSync('sessionTimeStamp', new Date().getTime())
          uni.setStorageSync('step', 0)
          uni.setStorageSync('flowAnalysisLogDto', '')
          this.$Router.pushTab('/pages/index/index')
        }
      })
    },
    nono () { }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  onPullDownRefresh: function () {

  },
  onShareAppMessage: function (e) {
    return {

    };
  },
};
</script>
<style>
@import "./personal-information.css";
</style>
